package com.shinhye.elephantsafe.service;

import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;

public class AutoKillService extends Service {
	private String TAG = "AutoKillService";
	private LockScreenReceiver receiver;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		Log.i(TAG, "服务开启了");
		//注册广播接收者
		receiver = new LockScreenReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_SCREEN_OFF);
		registerReceiver(receiver, filter);
	}
	
	/**
	 * Receiver the lock screen broadcast to auto kill processes.
	 * @author ShinHye
	 *
	 */
	private class LockScreenReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.i(TAG, "收到锁屏广播了！开始杀死进程！");
			
			ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
			List<RunningAppProcessInfo> list = am.getRunningAppProcesses();
			for (RunningAppProcessInfo info : list) {
				am.killBackgroundProcesses(info.processName);
			}
		}
	}
	
	@Override
	public void onDestroy() {
		Log.i(TAG, "服务关闭了");

		//取消注册广播接收者
		unregisterReceiver(receiver);
		receiver = null;
	}
}
